const { baseURL, token } = getApp()
import Toast from '../miniprogram_npm/@vant/weapp/toast/toast'
export const request = function (url, params, loading) {
  let loadingObj = {
    message: '...加载中',
    loading: true
  }
  Object.assign(loadingObj, loading || {})

  if (token) {
    params.token = token
  }

  if (loadingObj.loading) {
    Toast.loading({
      message: loadingObj.message || '...加载中',
      forbidClick: true,
      duration: 0
    });
  }
  let method = 'POST'
  if (params && Object.prototype.toString.call(params) !== "[object Object]") {
     throw new Error('参数格式有误')
  }
  if (params && params.method) {
    method = params.method.toUpperCase()
    delete params.method

    if (method !== 'POST' && method !== 'GET') {
      throw new Error('请求方式错误')
    }
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${baseURL}${url}`,
      method,
      data: params,
      header: {
        'content-type': 'application/json'
      },
      success(res) {

        const {
          statusCode,
          data
        } = res
        Toast.clear()
        if (statusCode >= 200 && statusCode < 300 || statusCode === 304) {
          resolve(data)

        } else {
          Toast('服务器繁忙，请稍后重试')
        }
      },
      fail(error) {
        Toast('网络异常或服务器繁忙，请稍后重试')
        reject(error.data)
      }
    })
  })

}